//
//  CZEmticonTool.swift
//  WeiBO28
//
//  Created by 飞奔的羊 on 16/5/20.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
enum CZEmticonToolBarButtonType: Int {
	case Normal = 1000
	case Emoji = 1001
	case Lxh  = 1002
}
///表情键盘
class CZEmticonTool:  UIStackView {
	var lastSelectedButton: UIButton?
	//定义点击表情按钮的闭包
	var didSelectedEmoticonButtonClosur:((type: CZEmticonToolBarButtonType)->())?
	
	
	override init(frame: CGRect) {
		super.init(frame: frame)
		setUpUI()
	}
	
	required init?(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
	
	private func setUpUI(){
	
		
		axis = .Horizontal
		distribution = .FillEqually

	addChildBUtton("默认", bgImage: "compose_emotion_table_left", type: .Normal)
		addChildBUtton("Emoji", bgImage: "compose_emotion_table_mid", type: .Emoji)
		addChildBUtton("浪小花", bgImage: "compose_emotion_table_right", type: .Lxh)

	}
	private func addChildBUtton(title: String, bgImage: String, type: CZEmticonToolBarButtonType) {
	let button = UIButton()
		button.tag = type.rawValue
		button.addTarget(self, action: #selector(CZEmticonTool.emoticonButtonClick(_:)), forControlEvents: .TouchUpInside)
		
		button.setTitle(title, forState: .Normal)
	button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
		button.setTitleColor(UIColor.grayColor(), forState: .Selected)
		//字体大小
		button.titleLabel?.font = UIFont.systemFontOfSize(15)
		button.setBackgroundImage(UIImage(named: "\(bgImage)_normal"), forState: .Normal)
		button.setBackgroundImage(UIImage(named: "\(bgImage)_selected"), forState: .Selected)
		//去掉高亮效果
		button.adjustsImageWhenHighlighted = false
		addArrangedSubview(button)
		if type == .Normal {
			lastSelectedButton?.selected = false
			button.selected = true
			lastSelectedButton = button
		}
	}
// MARK: ------点击事件------
	@objc private func emoticonButtonClick(button: UIButton) {
	
		if button == lastSelectedButton {
			return
		}
		//取消上一次选中的状态
		lastSelectedButton?.selected = false
	
		button.selected = true
		//记录选中按钮
		lastSelectedButton = button
		//通过
		let type = CZEmticonToolBarButtonType(rawValue: button.tag)!
		didSelectedEmoticonButtonClosur?(type: type)
	}
	//根据传入的 section 判断选中哪个按钮
	func selectEmoticonButtonWithSection(section: Int) {
		//根据 tag 值判断是都同一个按钮,如果是,不需要选中
		if section + 1000 == lastSelectedButton?.tag {
			return
		}
		
		//如果 tag 是0娶不到按钮,是当前控件
		let button = viewWithTag(section + 1000) as! UIButton
		lastSelectedButton?.selected = false
		button.selected = true
		lastSelectedButton = button
	}
}




























